package com.hjm.project.merchantInfo.merchantInfo.util;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.common.utils.request.AutoLoadData;
import com.hjm.common.utils.request.HttpClientUtil;
import com.hjm.common.utils.yh.Utils;
import com.hjm.framework.config.CustomConfig;
import com.hjm.project.merchantInfo.merchantInfo.domain.MerchantInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class UpdateMerUtils {
    public static JSONObject updateMerchant(Map<String, String> params, String merno, MerchantInfo merchantInfo1, List<String> imgMap,String mchtStatus) throws Exception {

        //商户请求信息
        JSONObject request1 = new JSONObject();
        String merName = merchantInfo1.getMerName();
        request1.put("settlTN", "0");
        request1.put("mchtNo", merno);
        request1.put("termNm", merName);
        request1.put("contact", params.get("screenName"));                                 //法人姓名
        request1.put("managerActCon", params.get("screenName"));                           //法人姓名
        request1.put("manager", params.get("screenName"));                                 //法人姓名
        request1.put("settleAcctNm", params.get("screenName"));
        request1.put("settleAcctNo", params.get("screenNum"));
        request1.put("settleIdentifyNo", params.get("screenIdnum"));
        request1.put("settleBindTel", params.get("resphone"));
        request1.put("certExpdate", params.get("time").replaceAll("-",""));

        Map<String, Object> requestMap = Maps.newHashMap();
        requestMap.put("mchtJson", JSONObject.toJSONString(request1));
        requestMap.put("brhJson", getPartnerJson());
        //处理商户图片信息节点
        requestMap.put("fileData",createFileDate(merno,imgMap));
        //发送请求
        System.out.println(requestMap);
        String getMerchant = "";
        if (mchtStatus.equals("0")){
            getMerchant = HttpClientUtil.doPost(AutoLoadData.sendLdMerSyncMes, requestMap);
        } else {
            getMerchant = HttpClientUtil.doPost(AutoLoadData.sendLdMerSync, requestMap);
        }
        System.out.println("响应===============》" + getMerchant);
        return (JSONObject.parseObject(getMerchant));
    }

    public static final String ZIP = ".zip";

    private static String[] folderArray = {"upload", "upload1", "upload2", "upload3", "upload4", "upload5", "upload6",
            "upload7", "upload8", "upload10", "upload12", "upload13", "upload25"};

    /**
     * 生成钱宝图片数据
     * @param  merno
     * @return String
     */
    public static String createFileDate(String merno, List<String> imgMap) throws Exception{
        String pathName = "";
        System.out.println(imgMap);
        //内部路径2043-09-27
        JSONObject upload3 = new JSONObject();
        upload3.put("fileContent", CustomConfig.getImgUrl() + imgMap.get(0));
        upload3.put("fileContent1",CustomConfig.getImgUrl() + imgMap.get(1));
        JSONObject upload10 = new JSONObject();
        upload10.put("fileContent",CustomConfig.getImgUrl() + imgMap.get(2));

        //外部
        JSONObject imageMap = new JSONObject();
        imageMap.put("upload3",upload3);
        imageMap.put("upload10",upload10);
        File zipFile = null;
        ZipOutputStream zos = null;
        FileOutputStream fos = null;
        //图片存放路径
        //合作伙伴号
        String partnerNo = merno;
        String zipName = AutoLoadData.temporaryfile+partnerNo+  ZIP;
        try {
            zipFile = new File(zipName);
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(fos);
            String topFolderName = partnerNo +File.separator;
            //生成文件夹
            ZipEntry topEntity = new ZipEntry(topFolderName);
            zos.putNextEntry(topEntity);
            for (String folderName : folderArray) {
                Object obj = imageMap.get(folderName);
                if (ObjectUtils.allNotNull(obj)){
                    String folderPath = topEntity + folderName+File.separator;
                    //生成文件夹
                    ZipEntry foldEntity = new ZipEntry(folderPath);
                    zos.putNextEntry(foldEntity);
                    JSONObject fileMap = JSONObject.parseObject(JSONObject.toJSONString(obj));
                    for (String fileName : fileMap.keySet()) {
                        //图片路径
                        String filePath = String.valueOf(fileMap.get(fileName));
                        //将本地文件或则网络文件读取成byte数组
                        byte [] data= urlOrPathToByte(filePath);
                        //图片压缩
                        data = compressUnderSize(data, 1024*1024L);
                        if (data.length > 0){
                            //文件存在生成文件
                            pathName = filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
                            ZipEntry zipEntry = new ZipEntry(folderPath+pathName);
                            zos.putNextEntry(zipEntry);
                            zos.write(data);
                        }
                    }
                }
            }
            zos.closeEntry();
            //关闭流
            close(null, zos, fos);
            return byteToString(urlOrPathToByte(zipName));
        }finally {
            //关闭流
            close(null, zos, fos);
            //删除临时文件
            if (zipFile != null){
                zipFile.delete();
            }
        }
    }

    public static void close(InputStream inputStream, OutputStream... outputStreams) throws Exception{
        if (ObjectUtils.allNotNull(inputStream)){
            inputStream.close();
        }
        for (OutputStream outputStream : outputStreams) {
            if (ObjectUtils.allNotNull(outputStream)){
                outputStream.flush();
                outputStream.close();
            }
        }

    }

    /**
     * 图片上传，返回图片集合
     * @param request
     * @param createName
     * @return
     * @throws Exception
     */
    public static Map uploadImgInSync(HttpServletRequest request, String createName)throws Exception{
        Map imgMap = new HashMap();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile img = multiRequest.getFile(iter.next().toString());
                if (img != null && img.getSize() != 0) {
                    //将文件转化为 file类型
                    String hou = img.getOriginalFilename();
                    hou = hou.substring(hou.indexOf("."), hou.length());
                    //图片查看路径
                    Map<String, Object> params = new HashMap<String, Object>();

                    //上传文件 到 fastdfs
                    String fileName=img.getName() + hou;

                    File dfile = null;
                    dfile = File.createTempFile("prefix", "_" + img.getOriginalFilename());
                    img.transferTo(dfile);

                    Map<String,String> metaList = new HashMap<String, String>();
                    metaList.put("fileName",fileName);
                    metaList.put("fileType",img.getName());
                    metaList.put("author",createName);
                    metaList.put("date", Utils.formateDate(2));//年月日 时分秒
                    String fid = FastDFSClient.uploadFile(dfile,dfile.getName(),metaList);
                    imgMap.put(fileName,fid);
                }
            }
        }
        return imgMap;
    }


    /**
     * 将图片压缩到指定大小以内
     *
     * @param srcImgData 源图片数据
     * @param maxSize 目的图片大小
     * @return 压缩后的图片数据
     */
    public static byte[] compressUnderSize(byte[] srcImgData, long maxSize) {
        double scale = 0.9;
        byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length);
        if (imgData.length > maxSize) {
            do {
                try {
                    imgData = compress(imgData, scale);
                } catch (IOException e) {
                    throw new IllegalStateException("压缩图片过程中出错，请及时联系管理员！", e);
                }
            } while (imgData.length > maxSize);
        }
        return imgData;
    }

    /**
     * 按照 宽高 比例压缩
     * @param scale 压缩刻度
     * @return 压缩后图片数据
     * @throws IOException 压缩图片过程中出错
     */
    public static byte[] compress(byte[] srcImgData, double scale) throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        // 源图宽度
        int width = (int) (bi.getWidth() * scale);
        // 源图高度
        int height = (int) (bi.getHeight() * scale);

        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        // 绘制处理后的图
        g.drawImage(image, 0, 0, null);
        g.dispose();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bOut);
        return bOut.toByteArray();
    }

    /**
     * 将文件路径读取成二进制流
     * @param filePath String 文件路径
     * @return byte
     * @throws Exception e
     */
    private static byte[] urlOrPathToByte(String filePath) throws Exception{
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            if (filePath==null){
                return new byte[0];
            }
            String lowerCase = filePath.toLowerCase();
            try {
                if (lowerCase.startsWith(HttpClientUtil.PREFIX)){
                    //网络文件
                    URL url = new URL(filePath);
                    in = new BufferedInputStream(url.openStream());
                }else{
                    //本地文件
                    in = new FileInputStream(filePath);
                }
            }catch (Exception e){
                return new byte[0];
            }

            out = new ByteArrayOutputStream(1024);
            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            return out.toByteArray();
        }finally {
            close(in, out);
        }
    }


    /**
     * 二进制流转Base64字符串
     * @param data 二进制流
     * @return data
     * @throws IOException 异常
     */
    public static String byteToString(byte[] data) throws IOException {
        return Base64.getEncoder().encodeToString(data);
    }



    /**
     * 获取钱宝请求机构信息
     * @return String
     */
    public static String getPartnerJson(){
        return getPartnerJsonObject().toJSONString();
    }

    /**
     * 获取钱宝请求机构信息
     * @return String
     */
    public static JSONObject getPartnerJsonObject(){
        JSONObject partnerMap = new JSONObject();
        partnerMap.put("brhNo", "61025001");
        partnerMap.put("oprId", "admin");
        partnerMap.put("password", "aaaa1111");
        return partnerMap;
    }




}
